<?php

namespace Lesson\Controller;

use Common\Controller\AdminbaseController;
use Lesson\Model\RedeemCodeModel;

class AdminlessonController extends AdminbaseController {

    protected $page_size;
    function _initialize() {
        parent::_initialize();
        $this->page_size = 10;
    }

    // 课程专题列表
    public function subject_lists()
    {
        // 名字模糊搜索
        $keyword = I('request.keyword');
        if(!empty($keyword)) {
            $where['subject_name'] = array('like', "%$keyword%");
        }
        $model  = M('lesson_subject');
        $count  = $model->count();
        $page   = $this->page($count, $this->page_size);
        $lists  = $model->order('sort desc, created_at desc')->select();

        $this->assign("page", $page->show('Admin'));
        $this->assign("formget", array_merge($_GET, $_POST));
        $this->assign("lists", $lists);
        $this->display();
    }

    // 新增，编辑 课程专题
    public function edit_lesson_subject()
    {
        $id = I('get.id');
        if (IS_POST) {
            $subject = I('post.subject');
            $subject['subject_img'] = sp_asset_relative_url($_POST['smeta']['thumb']);
            $subject['subject_pc_img'] = sp_asset_relative_url($_POST['smeta']['thumb_pc_img']);
            $subject['subject_mobile_img'] = sp_asset_relative_url($_POST['smeta']['thumb_mobile_img']);

            $id = $id ?: $subject['id'];
            if ($id) {
                M('lesson_subject')->where(['id' => $id])->save($subject);
            } else {
                unset($subject['id']);
                $subject['created_at'] = time();
                M('lesson_subject')->add($subject);
            }
            $this->success('操作成功');

        } else {
            $subject = M('lesson_subject')->where(['id' => $id])->find();
            if ($subject) {
                $del = I('get.del');
                if ($del) {
                    M('lesson_subject')->where(['id' => $id])->delete();
                    $has_lesson = M('lesson')->where(['subject_id' => $id])->find();
                    if ($has_lesson) {
                        $this->error('该专题下还有课程，暂时不能删除');
                    } else {
                        $this->success('操作成功');
                    }
                }
                $this->assign('subject', $subject);
            }
            $this->display();
        }
    }

    // 课程列表
    public function lesson_lists()
    {
        // 名字模糊搜索
        $keyword = I('request.keyword');
        if(!empty($keyword)) {
            $where['l.lesson_name'] = array('like', "%$keyword%");
        }

        // 专题名称
        $subject_name = I('request.subject_name');
        if(!empty($subject_name)) {
            $where['ls.subject_name'] = array('like', "%$subject_name%");
        }

        // 行家名称
        $lecture_user_name = I('request.lecture_user_name');
        if(!empty($lecture_user_name)) {
            $where['u.user_nicename'] = array('like', "%$lecture_user_name%");
        }

        $model  = M('lesson');
        $count  = $model
            ->alias('l')
            ->join('__LESSON_SUBJECT__ ls on ls.id = l.subject_id', 'left')
            ->join('__USERS__ u on u.id = l.lecturer_user_id', 'left')
            ->where($where)
            ->count();
        $page   = $this->page($count, $this->page_size);
        $lists  = $model
            ->alias('l')
            ->join('__LESSON_SUBJECT__ ls on ls.id = l.subject_id', 'left')
            ->join('__USERS__ u on u.id = l.lecturer_user_id', 'left')
            ->where($where)
            ->limit($page->firstRow , $page->listRows)
            ->field('l.*, u.user_nicename, ls.subject_name')
            ->select();

        $this->assign("page", $page->show('Admin'));
        $this->assign("formget", array_merge($_GET, $_POST));
        $this->assign("lists", $lists);
        $this->display();
    }


    // 新增，编辑 课程
    public function edit_lesson()
    {
        $id = I('get.id');
        if (IS_POST) {
            $lesson = I('post.lesson');
            $lesson['lesson_img']           = sp_asset_relative_url($_POST['smeta']['thumb']);
            $lesson['lesson_audio_img']     = sp_asset_relative_url($_POST['smeta']['audio_thumb']);
            $lesson['lesson_file']          = json_encode(['lesson_file_path' => $lesson['lesson_file_path'], 'lesson_file_name' => $lesson['lesson_file_name']]);

            // 标签
            $labels = $lesson['labels'];
            $labels = array_filter(explode(',', $labels));
            if (empty($labels)) {
                $this->error("请至少选择一个标签！");
            }
            $lesson['labels'] = implode(',', $labels);

            $id = $id ?: $lesson['id'];
            if ($id) {
                M('lesson')->where(['id' => $id])->save($lesson);
            } else {
                unset($lesson['id']);
                $lesson['created_at'] = time();
                $result = M('lesson')->add($lesson);

                // 主动提交百度seo链接
                if (C('PUSH_SEO_URL')) {
                    $urls = array(C('HTTP_METHOD') . C('DOMAIN_NAME') . U('Lesson/Lesson/lesson_index', ['id' => $result]));
                    post_baidu_seo_url($urls);
                }
            }
            $this->success('操作成功');

        } else {
            $lesson = M('lesson')
                ->where(['id' => $id])
                ->field('*, (select GROUP_CONCAT(name) FROM rx_label where FIND_IN_SET(id, labels) order by id) as label_names')
                ->find();
            if ($lesson) {
                $del = I('get.del');
                if ($del) {
                    M('lesson')->where(['id' => $id])->delete();
                    $this->success('操作成功');exit();
                }
                if (!empty($lesson['labels'])) {
                    $lesson['label_names'] = array_filter(explode(',', $lesson['label_names']));
                } else {
                    $lesson['label_names'] = [];
                }
                $lesson['lesson_file'] = json_decode($lesson['lesson_file'], true);
                $this->assign('lesson', $lesson);
            }
            // 课程专题
            $subject_lists = M('lesson_subject')->order('sort desc, created_at desc')->limit(0)->select();
            $this->assign('subject_lists', $subject_lists);
            // 行家
            $professor_lists = M('professor')
                ->alias('p')
                ->join("__USERS__ u on u.id = p.user_id", 'left')
                ->where(['p.del_time' => 0, 'p.status' => 1])
                ->field('u.id, u.user_nicename, u.user_login')
                ->order('p.pf_order desc, p.created_at desc')
                ->limit(0)
                ->select();
            $this->assign('professor_lists', $professor_lists);
            // 云存储视频
            $video_lists = M('video')->limit(0)->order('created_at desc')->select();
            $this->assign('video_lists', $video_lists);

            $this->display();
        }
    }

    // 轻咨询行家列表
    public function lesson_pf_lists()
    {
        // 行家列表
        $pf_lists = M('professor')
            ->alias('p')
            ->join('__USERS__ u on u.id = p.user_id', 'left')
            ->field('p.advisory_sort, p.advisory, p.id, u.user_nicename, u.position, u.company, u.avatar')
            ->where(['p.status' => 1, 'p.del_time' => 0])
            ->order('p.advisory_sort desc, p.pf_order desc')
            ->limit(0)
            ->select();

        $this->assign('pf_lists', $pf_lists);
        $this->display();
    }

    // 修改开通轻咨询行家列表
    public function edit_lesson_pf_lists()
    {
        $id = I('id');
        $op = I('op'); // 操作

        if ($op == 'add') {
            $advisory = 1;
        } else {
            $advisory = 0;
        }
        M('professor')->where(['id' => $id])->save(['advisory' => $advisory]);
        $this->success('操作成功');
    }

    // 查看专题的兑换码列表
    public function lesson_subject_redeem_code_list()
    {
        $subject_id = I('lesson_subject_id', 0);
        if ($subject_id) {
            $redeem_code_model  = D('Lesson/RedeemCode');
            $where              = ['type' => RedeemCodeModel::redeem_code_type_lesson_subject, 'related_id' => $subject_id];
            $count              = $redeem_code_model->where($where)->count();
            $page               = $this->page($count, $this->page_size);
            $lists              = $redeem_code_model->where($where)->limit($page->firstRow , $page->listRows)->select();

            $this->assign('lists', $lists);
            $this->assign('subject_id', $subject_id);
            $this->assign("page", $page->show('Admin'));
            $this->display();
        } else {
            $this->error("参数错误");
        }
    }

    // 生成专题相关兑换码
    public function create_lesson_redeem_code()
    {
        $subject_id = I('subject_id', 0);
        $num        = I('num', 0);
        $discount   = I('discount', 0);
        $result     = array();
        if ($subject_id && $num && $discount >= 0) {
            $subject    = M('lesson_subject')->where(['id' => $subject_id])->find();
            if ($subject) {
                $redeem_code_model  = D('Lesson/RedeemCode');
                $real_num           = min(100, $num);
                $redeem_code_list   = array();
                for ($i = 0; $i < $real_num; $i++) {
                    $code       = get_inc_no('redeem_code');
                    $code       = substr(md5($code), 0, 8);
                    $old_info   = $redeem_code_model->where(['code' => $code, 'type' => RedeemCodeModel::redeem_code_type_lesson_subject])->find();
                    if (!$old_info) {
                        $data = array(
                            'code'          => $code,
                            'type'          => RedeemCodeModel::redeem_code_type_lesson_subject,
                            'related_id'    => $subject_id,
                            'discount'      => $discount,
                            'user_id'       => 0,
                            'use_time'      => 0,
                            'created_at'    => time(),
                        );
                        $redeem_code_list[] = $data;
                    } else {
                        $i--;
                    }
                }
                $redeem_code_model->addAll($redeem_code_list);
                $result['status']   = 1;
                $result['info']     = '操作成功！';
                $this->ajaxReturn($result);
            } else {
                $result['info'] = '未找到专题';
                $this->ajaxReturn($result);
            }
        } else {
            $result['info'] = '参数错误';
            $this->ajaxReturn($result);
        }
    }

    // 删除兑换码
    public function delete_redeem_code()
    {
        $id = I('id', 0);
        $result = array();
        if ($id) {
            $redeem_code = M('redeem_code')->where(['id' => $id])->find();
            if ($redeem_code) {
                if ($redeem_code['use_time'] == 0) {
                    M('redeem_code')->where(['id' => $id])->delete();
                    $result['status']   = 1;
                    $result['info']     = '操作成功！';
                    $this->ajaxReturn($result);
                } else {
                    $result['info'] = '该兑换码已被使用';
                    $this->ajaxReturn($result);
                }
            } else {
                $result['info'] = '未找到兑换码';
                $this->ajaxReturn($result);
            }
        } else {
            $result['info'] = '参数错误';
            $this->ajaxReturn($result);
        }
    }

    public function change_subject_sort()
    {
        $id     = I('id', 0, 'intval');
        $order  = I('order', 0, 'intval');

        if ($id) {
            M('lesson_subject')->where(['id' => $id])->save(['sort' => $order]);
            $this->success('修改成功');
        }
    }

    public function change_lesson_sort()
    {
        $id     = I('id', 0, 'intval');
        $order  = I('order', 0, 'intval');

        if ($id) {
            M('lesson')->where(['id' => $id])->save(['sort' => $order]);
            $this->success('修改成功');
        }
    }

    public function change_pf_advisory_sort()
    {
        $id     = I('id', 0, 'intval');
        $order  = I('order', 0, 'intval');

        if ($id) {
            M('professor')->where(['id' => $id])->save(['advisory_sort' => $order]);
            $this->success('修改成功');
        }
    }
}
